package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zsk
 * @create 2022-04-11-12:33
 */
@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {


    /**
     * 过滤器执行逻辑
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求url
        String url = request.getURI().getPath();

        //判断是否需要鉴权
        if (url.contains("/login")){//如果是登录请求
            return chain.filter(exchange);//直接放行
        }
        //判断token是否存在
        String token = request.getHeaders().getFirst("token");
        if (token == null){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();//返回401
        }
        //判断token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            //判断此时result的状态
            if (result == -1 || result == 0){
                //有效，将用户id放入到token中，转发到后续微服务中，放行
                Object userId = claims.get("userId");
                request.mutate().header("userId",userId.toString());
                return chain.filter(exchange);//放行
            }

        } catch (Exception e) {

            //记录日志信息
            log.info(e.getMessage());
        }

        //其他情况，统一返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器执行优先级，数字越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
